package org.algorithm;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESFinal {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String ENCODING = "UTF-8";

    private static final String SECRET_KEY = "1234567890abcdef"; // 密钥长度应为16个字符
    private static final String IV = "1234567890abcdef"; // 初始化向量长度应为16个字符

    public static byte[] encrypt(String valueToEncrypt) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(128, new SecureRandom(SECRET_KEY.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(ENCODING));

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        return cipher.doFinal(valueToEncrypt.getBytes(ENCODING));
    }

    public static String decrypt(byte[] encryptedValue) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(128, new SecureRandom(SECRET_KEY.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(ENCODING));

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

        return new String(cipher.doFinal(encryptedValue), ENCODING);
    }

    public static void main(String[] args) {
        try {
            String originalString = "This is a secret message!";
            System.out.println("Original String: " + originalString);

            byte[] encrypted = encrypt(originalString);
            System.out.println("Encrypted String: " + Base64.getEncoder().encodeToString(encrypted));

            String decryptedString = decrypt(encrypted);
            System.out.println("Decrypted String: " + decryptedString);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
